package com.yang.library.client.menu;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yang.library.bookenum.TCPEnum;
import com.yang.library.bookenum.State;
import com.yang.library.entry.Book;
import com.yang.library.util.AppContext;
import com.yang.library.util.Constant;
import com.yang.library.util.PrintUtils;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class AdminBookMenu implements Menu {
    private final ObjectMapper mapper = AppContext.getInstance().getMapper();
    private final Socket socket;

    public AdminBookMenu(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void start() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
            while (true) {
                System.out.println("=========欢迎来到图书系统管理员界面==========");
                System.out.println("1. 添加图书");
                System.out.println("2. 删除图书");
                System.out.println("3. 修改图书");
                System.out.println("4. 根据图书名称或者作者名查找图书");
                System.out.println("5. 显示所有图书");
                System.out.println("6. 显示所有被借阅图书");
                System.out.println("7. 图书系统用户管理(管理员)");
                System.out.println("8. 退出图书系统管理员界面");

                int type = PrintUtils.getIntInput(AppContext.getInstance().getScanner(), "请输入您的选择:");
                switch (type) {
                    case 1:
                        addBook(reader, writer);
                        break;
                    case 2:
                        removeBook(reader, writer);
                        break;
                    case 3:
                        updateBook(reader, writer);
                        break;
                    case 4:
                        getBookByTitleOrAuthor(reader, writer);
                        break;
                    case 5:
                        getAllBooks(reader, writer);
                        break;
                    case 6:
                        getAllBorrowedBooks(reader, writer);
                        break;
                    case 7:
                        new AdminUserManagementMenu(socket).start();
                        break;
                    case 8:
                        return;
                    default:
                        System.out.println("输入错误，请重新输入");
                        break;
                }
            }
        } catch (Exception e) {
            System.out.println("图书系统管理员界面异常");
            throw new RuntimeException(e);
        }
    }

    private void getAllBorrowedBooks(BufferedReader reader, BufferedWriter writer) throws Exception {
        // 向服务端发送查询请求
        writer.write(mapper.writeValueAsString(TCPEnum.QUERY_ALL_BORROWED_BOOK) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        List<Book> books = mapper.readValue(responseMsg, new TypeReference<>() {
        });
        if (books == null || books.isEmpty()) {
            System.out.println("没有找到图书");
            return;
        }
        PrintUtils.printBooks(books);
    }

    private void getAllBooks(BufferedReader reader, BufferedWriter writer) throws Exception {
        // 向服务端发送查询请求
        writer.write(mapper.writeValueAsString(TCPEnum.QUERY_ALL_BOOK) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        List<Book> books = mapper.readValue(responseMsg, new TypeReference<>() {
        });
        if (books == null || books.isEmpty()) {
            System.out.println("没有找到图书");
            return;
        }
        PrintUtils.printBooks(books);
    }

    private void getBookByTitleOrAuthor(BufferedReader reader, BufferedWriter writer) throws Exception {
        String titleOrAuthor = PrintUtils.getInput("请输入书名或作者");
        // 向服务端发送查询请求
        writer.write(mapper.writeValueAsString(TCPEnum.QUERY_BOOK_BY_TITLE_OR_AUTHOR) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(titleOrAuthor) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        List<Book> books = mapper.readValue(responseMsg, new TypeReference<>() {
        });
        if (books == null || books.isEmpty()) {
            System.out.println("没有找到图书");
            return;
        }
        PrintUtils.printBooks(books);
    }

    private void updateBook(BufferedReader reader, BufferedWriter writer) throws Exception {
        String title = PrintUtils.getInput("请输入要更新的图书名称:");
        String[] info = PrintUtils.getInput("请输入要更新作者名称，IBN号:").split("[,，]");
        Book book = new Book(title, info[0], info[1], false, null, null, null, null);
        // 向服务端发送修改数据的请求
        writer.write(mapper.writeValueAsString(TCPEnum.UPDATE_BOOK) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(title) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(book) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        State response = mapper.readValue(responseMsg, State.class);
        switch (response) {
            case SUCCESS:
                System.out.println("修改成功!");
                break;
            case FAILURE:
                System.out.println("修改失败，图书不存在或图书已被借出！");
                break;
        }
    }

    private void removeBook(BufferedReader reader, BufferedWriter writer) throws Exception {
        String title = PrintUtils.getInput("请输入要删除的图书名称：");
        // 向服务端发送删除数据的请求
        writer.write(mapper.writeValueAsString(TCPEnum.REMOVE_BOOK) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(title) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        State response = mapper.readValue(responseMsg, State.class);
        switch (response) {
            case SUCCESS:
                System.out.println("删除成功！");
                break;
            case FAILURE:
                System.out.println("删除失败!图书不存在！");
                break;
        }
    }

    private void addBook(BufferedReader reader, BufferedWriter writer) throws Exception {
        String[] info = PrintUtils.getInput("请输入图书名称，作者名称，IBN号：").split("[,，]");
        Book book = new Book(info[0], info[1], info[2], false, null, null, null, null);
        // 向服务端发送添加数据的请求
        writer.write(mapper.writeValueAsString(TCPEnum.ADD_BOOK) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(book) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        State response = mapper.readValue(responseMsg, State.class);
        switch (response) {
            case SUCCESS:
                System.out.println("添加成功!");
                break;
            case FAILURE:
                System.out.println("添加失败!书名已存在！");
                break;
        }
    }
}
